package com.hanbang.chu_xing_gao_zhao.module;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.base.BaseActivity;
import com.hanbang.chu_xing_gao_zhao.myview.Singleness;
import com.hanbang.chu_xing_gao_zhao.myview.Singleness.OnClickCallback;
import com.hanbang.chu_xing_gao_zhao.utils.EditHelper;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class RegisterActivity extends BaseActivity {

	/** 编辑助手 */
	private EditHelper editHelper = new EditHelper(this);

	/** 验证码按钮倒计时 总时长和间隔时长，默认为60秒 */
	private long totalTime = 60000, intervalTime = 1000;

	/** 发送验证码 */
	private TextView sendVerificationCode;

	/** 查看注册协议 */
	private TextView registerTreaty;

	/** 验证码记录 */
	private String verificationCode = "11";

	/** 职位类型 */
	private String positionClassify = "null";

	/** 是否同意协议 */
	private CheckBox treatySelect;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		initView();
		setOnClickListener();
		SinglenessButton();
	}

	/**
	 * 初始化view
	 */
	private void initView() {

		treatySelect = (CheckBox) findViewById(R.id.register_agreement);
		sendVerificationCode = (TextView) findViewById(R.id.register_send_verification);

		editHelper.setEditText((EditText) findViewById(R.id.phone), // 加入手机号
				(EditText) findViewById(R.id.verificationCode),// 加入验证码
				(EditText) findViewById(R.id.password), // 加入密码
				(EditText) findViewById(R.id.password2));// 加入确认密码

		// 添加提示文本
		editHelper.setHintText("请正确输入手机号", "请输入短信验证码", "请输入最少6位密码", "请输入最少6位确认密码");

		// 添加最小值
		editHelper.setHintMinNumber(11, 1, 6, 6);

		registerTreaty = (TextView) findViewById(R.id.register_treaty);

	}

	/**
	 * 单选按钮的监听，与取值
	 */
	private void SinglenessButton() {

		Singleness s = new Singleness(this, (LinearLayout) findViewById(R.id.ll_1),
				(LinearLayout) findViewById(R.id.ll_2), (LinearLayout) findViewById(R.id.ll_3));

		s.setOnClickCallback(new OnClickCallback() {

			@Override
			public void onClick(Singleness Singleness, String content) {
				Toast.makeText(getApplicationContext(), "你选择了" + content, Toast.LENGTH_LONG).show();
				positionClassify = content;

			}
		});

	}

	/**
	 * 设置点击事件
	 */
	private void setOnClickListener() {
		findViewById(R.id.register_next).setOnClickListener(onClickListener);
		sendVerificationCode.setOnClickListener(onClickListener);
		registerTreaty.setOnClickListener(onClickListener);

	}

	/**
	 * 监听处理
	 */
	private OnClickListener onClickListener = new OnClickListener() {
		Intent intent = new Intent();

		@Override
		public void onClick(View v) {
			switch (v.getId()) {

			// 下一步的验证
			case R.id.register_next:

				if (!verificationCode.equals(((EditText) findViewById(R.id.verificationCode)).getText().toString())) {
					MyToast.show(RegisterActivity.this, "验证码不匹配", Toast.LENGTH_LONG);
					break;
					
				}

				if ((((EditText) findViewById(R.id.password)).getText().toString().trim()).equals("")
						|| (((EditText) findViewById(R.id.password2)).getText().toString().trim()).equals("")) {
					MyToast.show(RegisterActivity.this, "密码不能为空", Toast.LENGTH_LONG);
					break;
				}

				if (!((EditText) findViewById(R.id.password)).getText().toString().trim()
						.equals(((EditText) findViewById(R.id.password2)).getText().toString().trim())) {
					MyToast.show(RegisterActivity.this, "两次密码不一致", Toast.LENGTH_LONG);

					break;
				}

				if (positionClassify.equals("null")) {
					MyToast.show(RegisterActivity.this, "职位类型不能为空", Toast.LENGTH_LONG);
					break;
				}

				if (!treatySelect.isChecked()) {
					MyToast.show(RegisterActivity.this, "请同意服务协议", Toast.LENGTH_LONG);

					break;
				}

				// 跳转到完善资料页面
				intent.setClass(RegisterActivity.this, RegisterPerfectActivity.class);

				final ArrayList<String> data = editHelper.getText();
				intent.putExtra("phone", data.get(0));
				intent.putExtra("code", data.get(1));
				intent.putExtra("password0", data.get(2));
				intent.putExtra("password1", data.get(3));
				intent.putExtra("position", positionClassify);
//				Log.i("text", "*1111**" + data.get(0) + data.get(1) + data.get(2) + data.get(3));// *****
				startActivity(intent);

				break;

			// 发送验证码
			case R.id.register_send_verification:
				sendVerificationCode();
				break;

			// 跳转到注册协议页面
			case R.id.register_treaty:
				intent.setClass(RegisterActivity.this, RegisterTreatyActivity.class);
				startActivity(intent);
				break;

			default:
				break;
			}
		}
	};

	/**
	 * http://mrcm.hbung.com/tools/UserLogin.ashx?action=user_register&nickname=
	 * asa &mobile=19051196428&code=0532&password=123&againpassword=123 --注册
	 */
	private void register() throws IndexOutOfBoundsException {
		final ArrayList<String> res = editHelper.getText();

		RequestParams params = new RequestParams();
		params.addBodyParameter("action", "user_register");
		params.addBodyParameter("nickname", res.get(0));
		params.addBodyParameter("mobile", res.get(1));
		params.addBodyParameter("code", res.get(2));
		params.addBodyParameter("password", res.get(3));
		params.addBodyParameter("againpassword", res.get(4));

		httpUtils.send(HttpMethod.POST, HttpInterfaces.verificationNumber, params, new MyRequestCallBack<String>(this,
				"正在注册...") {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				super.onSuccess(responseInfo);
				try {
					JSONObject json = new JSONObject(responseInfo.result);
					int status = json.getInt("status");
					if (status == 1) {
						Intent intent = new Intent();
						intent.putExtra("phone", res.get(1));
						intent.putExtra("password", res.get(3));
						setResult(999, intent);
						finish();
					} else {
						MyToast.show(RegisterActivity.this, json.getString("msg"), Toast.LENGTH_LONG);
					}
				} catch (JSONException e) {
					e.printStackTrace();
					MyToast.show(RegisterActivity.this, "注册失败", Toast.LENGTH_LONG);
				}
			}
		});
	}

	/**
	 * 手机发送验证码
	 * 
	 * @throws IndexOutOfBoundsException
	 */
	private void sendVerificationCode() throws IndexOutOfBoundsException {

		final ArrayList<String> res = editHelper.getText();
		// 号码不为空并且长度为11位
		if (res.get(0) == null || res.get(0).equals("") || res.get(0).length() < 11) {
			MyToast.show(RegisterActivity.this, "请正确输入手机号！", Toast.LENGTH_LONG);
			return;
		}
		// 发送
		httpUtils.send(HttpMethod.GET, HttpInterfaces.verificationNumber + "&mobile=" + res.get(0),
				new MyRequestCallBack<String>(this, "正在发送验证码...") {
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(responseInfo.result);

							int status = json.getInt("Result");
							if (status == 0) {
								countDownTimer.start();

							}

							MyToast.show(RegisterActivity.this, json.getString("Msg"), Toast.LENGTH_LONG);
							if (!verificationCode.equals("")) {
								// 验证码清空
								verificationCode = "";
								// 添加新的验证码
								verificationCode = json.getString("code");
							}

						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				});
	}

	/**
	 * 记录当下剩余时间
	 */
	CountDownTimer countDownTimer = new CountDownTimer(totalTime, intervalTime) {
		@Override
		public void onFinish() {// 计时完毕时触发
			sendVerificationCode.setText("重新发送");
			sendVerificationCode.setEnabled(true);
			// authCodeButton.setClickable(true);
		}

		@Override
		public void onTick(long currentTime) {// 计时过程显示
			// authCodeButton.setClickable(false);
			sendVerificationCode.setEnabled(false);
			sendVerificationCode.setText(currentTime / 1000 + "秒");
		}
	};

	@Override
	protected void onResume() {
		// 设置顶部的标题
		setBackArrows(findViewById(R.id.bar_top_conver_classify_back));
		setTitleMore(View.VISIBLE, View.INVISIBLE, "用户注册", null, null, null);

		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
}
